import { createApp, ref, h } from 'vue'
import SimpleMessage from './SimpleMessage.vue'

let appMounted = false
const visibleRef = ref(false)
const messageRef = ref('')
const durationRef = ref(3000)
let hideTimer: number | null = null

function ensureMount() {
  if (appMounted) return
  const container = document.createElement('div')
  container.id = 'simple-message-container'
  document.body.appendChild(container)

  const app = createApp({
    setup() {
      return () =>
        h(SimpleMessage, {
          visible: visibleRef.value,
          message: messageRef.value,
          duration: durationRef.value,
        })
    },
  })

  app.mount(container)
  appMounted = true
}

export function showSimpleMessage(message: string, duration?: number) {
  ensureMount()
  messageRef.value = message
  durationRef.value = typeof duration === 'number' ? duration : 3000
  visibleRef.value = true
  // 自动隐藏（短暂消息）
  if (hideTimer !== null) {
    window.clearTimeout(hideTimer)
    hideTimer = null
  }
  if (durationRef.value > 0) {
    hideTimer = window.setTimeout(() => {
      visibleRef.value = false
      hideTimer = null
    }, durationRef.value)
  }
}

export function hideSimpleMessage() {
  if (hideTimer !== null) {
    window.clearTimeout(hideTimer)
    hideTimer = null
  }
  visibleRef.value = false
}

